#include "TaskDispatcher.h"


#include "Client.h"
#include "ClientManager.h"
#include "SysInit.h"
#include "ClassFactory.h"
#include "Demo.h"

#include <loong/TcpServer.h>
#include <loong/TcpConn.h>
#include <loong/Logger.h>
#include <loong/ThreadPool.h>

#include <unordered_map>
#include <iostream>


//---------------call back function------------------
const static int kMaxMessageLen = 64 * 1024 * 1024; // same as codec_stream.h kDefaultTotalBytesLimit
void onMessage(std::shared_ptr<loong::TcpConn> conn, loong::Buffer* buf)
{
	//DEBUG("read sockfd is: %d\n", conn->getSocket());
	printf("read sockfd is: %d\n", conn->getSocket());

	Client *client = static_cast<Client*>(conn->ptr);
	client->handleMsg(buf);
}

void onConn(std::shared_ptr<loong::TcpConn> conn)
{
	DEBUG("have client conn! %s", __FUNCTION__);
	Client *ptrCli = new Client(conn);
	conn->ptr = ptrCli;
}

void onClose(std::shared_ptr<loong::TcpConn> conn)
{
	DEBUG("have client close connect!");
	Client *cli = static_cast<Client*>(conn->ptr);
	ClientManager::instance()->delClient(cli->getClientId(), cli);
}

void onError(std::shared_ptr<loong::TcpConn> conn)
{
	DEBUG("have client close connect or network error!");
	Client *cli = static_cast<Client*>(conn->ptr);
	ClientManager::instance()->delClient(cli->getClientId(), cli);
}

void onThreadWork()
{
	std::deque<std::shared_ptr<Msg>> tmpQue;
	TaskDispatcher::getInstance()->getTask(tmpQue);

	while (!tmpQue.empty())
	{
		for (auto it = tmpQue.begin(); it != tmpQue.end(); it++)
		{
			ObjBase *obj = ClassFactory::getObject((*it)->cmd);
			if (obj == nullptr)
			{
				//命令没有定义
				cout<<"没有处理的消息类型"<<endl;
				continue;
			}
			obj->handle(*it);
		}
	}
}


int main()
{	
	sysInit();
	
	//类注册
	REGISTER_CLASS(Demo);
	
	//----------------------frame-begin-------------------------
	loong::ThreadPool *ptrThradPool = new loong::ThreadPool();
	INFO("start task process thread 8");
	ptrThradPool->setThreadWrokCallback(onThreadWork);
	//启动8个线程
	ptrThradPool->start(8);

	printf("start tcp server process\n");

	loong::TcpServer ts(8899);
	ts.setMessageCallback(onMessage);
	ts.setConnCallback(onConn);
	ts.setCloseCallback(onClose);
	ts.setErrCallback(onError);

	//启动一个IO线程;
	if (!ts.start())
	{
		ERROR("start server failed!\n");
		return 1;
	}
	printf("tcp server exit!\n");
	delete ptrThradPool;

	//----------------------frame-end---------------------------
	return 0;
}




